<template>
  <div class="task-wrapper" :style="{ 'height': documentClientHeight + 'px' }">
    <div class="left">
      <Menu :menuList="menuList" :title="'创建项目'" @selectMenu="selectTab" :hideCurMenu="!!curModuleId" @addOrUpdateProjectHandle="addOrUpdateProjectHandle" />
    </div>
    <add-or-update-project ref="AddOrUpdateProject" v-if="addOrUpdateVisible" @refresh="refreshDataList" @closeProjectDetail="closeProjectDetail"></add-or-update-project>
    <project-detail @changeHeight="changeHeight" ref="ProjectDetail" v-if="projectDetailVisible" @updateProject="addOrUpdateProjectHandle($event)" @refresh="refreshDataList"></project-detail>

    <div class="right">
      <div class="content-header">
        <span v-if="curModuleId">版块下的所有项目</span>
        <div v-if="!curModuleId" style="display: flex; justify-content:space-between; width: 100%;">
          <span v-if="currentIndex === 8">{{menuList[5].name}}</span>
          <span v-else-if="currentIndex === 6">{{menuList[currentIndex].name}}</span>
          <span v-else>{{menuList[currentIndex-1].name}}</span>
          <el-popover
          placement="bottom"
          title="筛选"
          width="330"
          trigger="click">
          <el-form label-width="80px" class="filter-form">
            <el-form-item label="版块">
              <el-select :multiple="true" :filterable="true" v-model="form.plateIds" placeholder="请选择版块" style="width: 100%;">
                <el-option style="width: 200px;" v-for="item in plateArr" :key="item.id" :label="item.plateName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目名称">
              <el-input placeholder="请输入项目名称" v-model="form.taskName"></el-input>
            </el-form-item>
            <el-form-item label="负责人">
              <div @click="selectDingUsers('plateProjectManagerIdArr','plateProjectManagerName','plateProjectManagerId', 'plateProjectAvator', 'plateProjectManagerNameArr')" class="select-btn"><span><i class="el-icon-plus"></i></span>添加</div>
              <div class="select-btn" v-for="(member, idx) in form.plateProjectManagerNameArr" :key="member" style="padding: 0;">{{member}}
                <div class="del" @click="delMember(idx)">移除</div>
              </div>
            </el-form-item>
            <el-form-item label="计划截止">
              <el-row>
                <el-date-picker v-model="form.filterStartPlanFinishTime" type="date" placeholder="项目计划结束起始日期" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
              </el-row>
              <el-row style="text-align: center;">至</el-row>
              <el-row>
                <el-date-picker v-model="form.filterEndPlanFinishTime" type="date" placeholder="项目计划结束截止日期" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getProjectList(true)">搜索</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
          <span class="filter" slot="reference">
            <img src="../../../assets/livolobim/filter.png">
            <div class="dot" v-if="hasSearchCondition"></div>
          </span>
        </el-popover>
        </div>
      </div>
      <div class="content-wrapper">
        <div v-if="currentIndex === 3 || currentIndex === 4 || currentIndex === 5 || currentIndex === 8">
          <div class="content-tab-bar" 
          v-for="item in subMenuList"
          :key="item.index">
            <div class="tab-item" @click="selectTab(currentIndex, item.index)" :class="{'active': currentSubIndex === item.index}">{{item.name}}</div>
          </div>
        </div>
        <div class="content" v-infinite-scroll="loadProject" infinite-scroll-disabled="disabled" infinite-scroll-immediate="false" :style="{ 'height': (this.currentIndex === 3 || this.currentIndex === 4 || this.currentIndex === 5 || this.currentIndex === 8)? 'calc(100% - 20px)': 'calc(100% + 20px)' }">
          <div class="project-wrapper" v-for="item in projectList" :key="item.id">
            <div class="task-item" @click="openProjectDetail(item.id)">
              <div class="tool">
                <i class="el-icon-setting" @click.stop="addOrUpdateProjectHandle(item.id)"></i>
              </div>
              <div v-if="item.taskDeleteStatus !== '4'">
                <span class="arrow-status" :class="'arrow-'+item.taskStatus"></span>
                <span class="task-status" v-if="item.taskStatus === '1'">待完成</span>
                <span class="task-status" v-if="item.taskStatus === '2'">待确认</span>
                <span class="task-status" v-if="item.taskStatus === '3'">已完成</span>
              </div>
              <div v-if="item.taskDeleteStatus === '4'">
                <span class="arrow-status" :class="'arrow-4'"></span>
                <span class="task-status">已归档</span>
              </div>
              <div class="top">
                <div class="logo">
                  <img :src="item.taskUrl? 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/project/'+item.taskUrl : 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/livolobim/project/icon%20orange-1.png'"  style="border-radius: 5px;width: 48px; height: 48px;">
                </div>
                <div class="task-info">
                  <p>{{item.taskName}}</p>
                  <p class="project"><span>{{item.taskBelongName}}</span></p>
                </div>
              </div>
                <div class="prograss">
                  <el-progress :percentage="item.statistics ? item.statistics.completePercent : 0" color="#4495FF"></el-progress>
                </div>
                <div class="bottom">
                  <p v-if="item.statistics">任务数：{{item.statistics.totalAmount}}
                    <span class="overdue" v-if="item.statistics.overdueAmount > 0">（逾期{{item.statistics.overdueAmount}}）</span>
                  </p>
                  <p v-else>任务数：0</p>
                  <p><i class="el-icon-user"></i>{{item.taskPrincipalName}}</p>
                </div>
            </div>
          </div>
          <img v-if="projectList.length === 0 && !isFirstLoading" style="width:200px;margin: auto;position:absolute;top:0;right:0;left:0;bottom: 0;" src="../../../assets/livolobim/empty.png" alt="">
        </div>
      </div>
      <div style="text-align: center;margin-top: 8px;color: #909399;">共有{{totalCount}}个项目</div>
    </div>
    <TaskDetail ref="TaskDetail" :taskDetailVisible.sync="projectDetailVisible" @closeSelf="closeTaskDetail" @refresh="getProjectList(true)"></TaskDetail>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from "@/utils/formUtil";
import Menu from './component/Menu'
import AddOrUpdateProject from './add-or-update-project'
import ProjectDetail from './project-detail'
import TaskDetail from './task-detail'

export default {
  data() {
    return {
      documentClientHeight: '',
      currentIndex: 1,
      currentSubIndex: 1,
      menuList: [{
        index: 1,
        name: '参与项目'
      },{
        index: 2,
        name: '关注项目'
      },{
        index: 3,
        icon: 'el-icon-folder-opened',
        isFolder: true,
        name: '可见项目'
      },{
        index: 4,
        name: '我负责的'
      },{
        index: 5,
        name: '我管理的'
      },{
        index: 8,
        name: '我确认的'
      },{
        index: 6,
        icon: 'el-icon-box',
        isFolder: true,
        name: '已归档项目'
      }],
      subMenuList: [{
        index: 1,
        name: '全部'
      },{
        index: 2,
        name: '待完成'
      },{
        index: 3,
        name: '待确认'
      },{
        index: 4,
        name: '已完成'
      }],
      addOrUpdateVisible: false,
      projectDetailVisible: false,
      projectList: [],
      plateIds: [],
      projectIds: [],
      isFirstLoading: true,
      loading: false,
      page: 1,
      limit: 30,
      totalPage: 1,
      totalCount: 0,
      form: {
        plateProjectManagerId: '',
        plateProjectManagerName: '',
        plateProjectAvator: [],
        plateProjectManagerNameArr: [],
        plateProjectManagerIdArr: [],
        plateIds: [],
        taskName: '',
        filterStartPlanFinishTime: null,
        filterEndPlanFinishTime: null,
      },
      formInit: {},
      curModuleId: '',
      plateArr: [],
    }
  },
  components: {
    Menu, AddOrUpdateProject, ProjectDetail, TaskDetail
  },
  mixins: [dingMixin],
  computed: {
    disabled () {
      return this.isFirstLoading || this.loading || this.noMore
    },
    noMore () {
      return this.page >= this.totalPage;
    },
    hasSearchCondition() {
      return JSON.stringify(this.form) !== this.formInit
    },
  },
  methods:{
    resetForm() {
      this.form = JSON.parse(this.formInit)
      this.getProjectList(true)
    },
    async getPlateList() {
      let {list} = await this.$httpN.postB('division/plate/list', {participateType: 2, limit: 999});
      this.plateArr = list;
    },
    selectDingUsers(ids, name, idsStr, avator, names){
      this.complexPicker(300, [], this.form[ids]).then((data)=>{
        this.form[ids] = data.map(item => item.emplId);
        this.form[avator] = data.map(item => item.avatar)
        this.form[names] = data.map(item => item.name)
        this.form[name] = this.form[names].join(',');
        this.form[idsStr] = this.form[ids].join(',')
      })
    },
    delMember(idx) {
      this.form.plateProjectAvator.splice(idx,1); 
      this.form.plateProjectManagerNameArr.splice(idx,1); 
      this.form.plateProjectManagerIdArr.splice(idx,1); 
      this.form.plateProjectManagerId = this.form.plateProjectManagerIdArr.join(',')
      this.form.plateProjectManagerName = this.form.plateProjectManagerNameArr.join(',')
    },
    loadProject() {
      this.loading = true;
      this.page ++;
      if (!this.curModuleId) {
        this.getProjectList();
      } else {
        this.getProjectListUnderModule();
      }
    },
    async selectTab(index, sectionType=1) {
      this.currentIndex = index;
      this.curModuleId = false;
      if (this.currentSubIndex !== sectionType) this.currentSubIndex = sectionType;
      formUtil.resetData(this.form);
      await this.getProjectList(true);
    },
    //新增或编辑项目
    addOrUpdateProjectHandle(id){
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.AddOrUpdateProject.init(id)
      })
    },
    //获取项目列表
    async getProjectList(init) {
      if(init) {
        this.page = 1;
        this.projectList = [];
        this.isFirstLoading = true;
      }
      var searchObj = {
        searchType: this.currentIndex,
        sectionType: this.currentIndex === 3 || this.currentIndex === 4 || this.currentIndex === 5 || this.currentIndex === 8 ? this.currentSubIndex : 1,
        filterPrincipalIds: this.form.plateProjectManagerId,
        taskName: this.form.taskName,
        plateIds: this.form.plateIds.join(','),
        filterStartPlanFinishTime: this.form.filterStartPlanFinishTime,
        filterEndPlanFinishTime: this.form.filterEndPlanFinishTime,
        page: this.page,
        limit: this.limit
      }
      let {list, totalPage, totalCount} = await this.$httpN.postB('division/task/filterProjectList', searchObj);
      this.plateIds = [];
      this.projectIds = [];
      list.forEach(item => {
        this.projectList.push(item);
        if(!this.plateIds.includes(item.taskBelongId))  this.plateIds.push(item.taskBelongId);
        this.projectIds.push(item.id);
      })
      await this.getAllStatistics(this.plateIds.join(','), this.projectIds.join(','));
      this.loading = false;
      if(init) {
        this.totalPage = totalPage;
        this.totalCount = totalCount;
        this.$nextTick(() => {
          this.isFirstLoading = false;
        })
      }
    },
    //获取版块下的下项目
    async getProjectListUnderModule(init) {
      if(init) {
        this.page = 1;
        this.projectList = [];
        this.isFirstLoading = true;
      }
      let {list, totalCount, totalPage} = await this.$httpN.postB('division/task/projectList', {
        searchType: 7,
        page: this.page,
        limit: this.limit,
        taskBelongId: this.curModuleId
      })
      this.projectIds = list.map(item => {
        return item.id
      })

      this.loading = false;
      this.projectList.push(...list);
      await this.getAllStatistics(this.curModuleId, this.projectIds.join(','));

      if(init) {
        this.totalPage = totalPage;
        this.totalCount = totalCount;
        this.$nextTick(() => {
          this.isFirstLoading = false;
        })
      }
    },
    async getAllStatistics(plateIds, projectIds) {
      await this.$httpN.postB('division/statistics/statisticsByCustomize', {plateIds: plateIds, projectIds: projectIds}).then(res => {
        let $this = this;
        this.projectIds.map(function(val,index) {
          let a = 0;
          res.map(function(val2) {
            if(val === val2.projectId) {
              $this.$set($this.projectList[$this.limit*($this.page-1)+index], 'statistics', val2);
              a++;
            }
          })
          if(a === 0) {
            $this.$set($this.projectList[$this.limit*($this.page-1)+index], 'statistics', {
              completePercent: 100,
              totalAmount: 0,
              overdueAmount: 0
            });
          }
        });
      })
    },
    //刷新列表
    refreshDataList() {
      this.getProjectList(true);
    },
    //关闭项目详情页
    closeProjectDetail() {
      this.projectDetailVisible = false;
    },
    //打开项目详情页
    openProjectDetail(id) {
      this.projectDetailVisible = true;
      this.$nextTick(() => {
         this.$refs.TaskDetail.init(id, 1);
      })
    },
    closeTaskDetail() {
      if(this.projectDetailVisible) this.projectDetailVisible = false;
    },
    changeHeight() {
      this.documentClientHeight = document.documentElement['clientHeight'] - 50
    }
  },
  async mounted() {
    this.documentClientHeight = document.documentElement['clientHeight'] - 50
    window.onresize = () => {
      this.documentClientHeight = document.documentElement['clientHeight'] - 50
    }
    if (this.$route.params.projectId) {
      this.$emit('changeTab', 2);
      this.openProjectDetail(this.$route.params.projectId);
    } else if (this.$route.query.moduleId) {
      this.$emit('changeTab', 2);
      this.curModuleId = this.$route.query.moduleId
      this.getProjectListUnderModule(true);
    } else {
      await this.getProjectList(true);
    }
    this.formInit = JSON.stringify(this.form)
    this.getPlateList()
  }
}
</script>

<style lang="scss" scoped>
  .content-wrapper .content::-webkit-scrollbar {/*滚动条整体样式*/
    width: 0px;     /*高宽分别对应横竖滚动条的尺寸*/
    height: 0px;
  }
  .task-wrapper{
    display:flex;
    .left{
      width: 250px;
      height: 100%;
      z-index: 1;
      background: #FFF;
      box-shadow: 3px 0 4px #F0F0F0;
    }
    .right{
      height: 100%;
      flex:1 ;
      .content-header{
        line-height: 50px;
        background: #FFF;
        font-size: 16px;
        font-weight: bold;
        padding: 0 25px;
        box-shadow: 0 3px 4px #F0F0F0;
        display: flex;
        justify-content:space-between;
        .filter {
          height: 50px;
          position: relative;
          > img {
            width: 24px;
            height: 24px;
            cursor: pointer;
            position: relative;
          }
          .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #4983FF;
            display: inline-block;
            vertical-align: super;
          }
        }
      }
      .content-wrapper{
        height: calc(100% - 80px);
        padding: 20px;
        .content-tab-bar{
          display: inline-block;
          >div{
            padding: 0 15px;
            margin-right: 10px;
            background: #ECECEC;
            line-height: 40px;
            text-align: center;
            color: #999CA1;
            border-radius: 5px 5px 0 0;
            cursor: pointer;
            span{
              padding: 0 6px;
              margin-left: 4px;
              background: #DBDBDC;
              border-radius: 8px;
              font-size: 12px;
            }
          }
          .active{
            box-shadow: 1px -1px 2px rgb(221, 221, 221);
            background: #FFF;
            color:#4983FF;
            font-weight: bold;
            span{
              background: #E4EDFF;
            }
          }
        }
        .content{
          height: calc(100% - 20px);
          box-shadow: 4px 4px 4px #dddddd;
          background-color: #FFF;
          z-index: 2;
          position: relative;
          overflow-y: auto;
          padding-bottom: 20px;
          .project-wrapper {
            width: 25%;
            float: left;
            padding: 20px;
            .task-item{
              position: relative;
              background: #FFF;
              width: 100%;
              height: 155px;
              box-sizing: border-box;
              border: 1px solid #D3E3E8;
              border-radius: 5px;
              box-shadow: 0px 0px 1px rgb(221, 221, 221);
              padding: 30px 45px;
              cursor: pointer;
              &:hover{
                box-shadow: 0px 0px 4px rgb(221, 221, 221);
              }
              &:hover .tool {
                display: block;
              }
              .tool {
                position: absolute;
                right: 25px;
                display: none;
                i {
                  font-size: 18px;
                  color: #79828C;
                }
              }
              .arrow-status{
                width:0;
                height:0;
                position: absolute;
                top: 0;
                left: 0;
                border-top-left-radius: 5px;
                border-top:solid 30px #4495FF;
                border-left:solid 30px #4495FF ;
                border-bottom:solid 30px transparent;
                border-right:solid 30px transparent;
                &.arrow-1{
                  border-top:solid 30px #4495FF;
                  border-left:solid 30px #4495FF ;
                }
                &.arrow-2{
                  border-top:solid 30px #E6A23C;
                  border-left:solid 30px #E6A23C ;
                }
                &.arrow-3{
                  border-top:solid 30px #B0C7CD;
                  border-left:solid 30px #B0C7CD ;
                }
                &.arrow-4{
                  border-top:solid 30px #909399;
                  border-left:solid 30px #909399 ;
                }
              }
              .task-status{
                position: absolute;
                width: 60px;
                line-height: 20px;
                left: -6px;
                top: 11px;
                color: white;
                font-size: 12px;
                transform: rotate(-45deg);
                text-align: center;
                font-weight: normal;
              }
              &::after{
                content: '';
                width:0;
                height:0;
                position: absolute;
                top: 0;
                left: 0;
                border-top-left-radius: 5px;
                border-top:solid 15px white;
                border-left:solid 15px white ;
                border-bottom:solid 15px transparent;
                border-right:solid 15px transparent;
              }
              .top{
                display:flex;
                margin-bottom: 10px;
                .logo{
                  width: 48px;
                  height: 48px;
                  text-align: center;
                  background: #E6A23C;
                  border-radius: 4px;
                  i{
                    line-height: 48px;
                    font-size: 30px;
                    color: #FFF;
                  }
                }
                .task-info{
                  p{
                    margin: 0;
                    padding-left:10px;
                    text-overflow: -o-ellipsis-lastline;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 1;
                    line-clamp: 1;
                    -webkit-box-orient: vertical;
                  }
                  .project{
                    margin-top: 15px;
                    span{
                      background: #FFDCDC;
                      color: #FF5050;
                      padding: 2px 6px;
                      border-radius: 3px;
                    }
                  }
                }
              }
              .bottom{
                margin-top: 10px;
                display: flex;
                flex-wrap: wrap;
                justify-content:space-between;
                align-content: flex-start;
                p{
                  margin: 5px 0 0 0 ;
                  color: #79828C;
                  i{
                    margin-right: 5px;
                  }
                }
                .overdue {
                  color: #FF5050;
                }
              }
            }
          }
        }
      }
    }
  }
  @media screen and (max-width: 1600px) {
    .task-wrapper .right .content-wrapper .content .project-wrapper {
      width: 33.3%;
    }
  }

  @media screen and (max-width: 1300px) {
    .task-wrapper .right .content-wrapper .content .project-wrapper {
      width: 50%;
    }
  }
  .select-btn{
    position: relative;
    float:left;
    font-weight: normal;
    margin-right: 5px;
    margin-bottom: 10px;
    width: 80px;
    height: 28px;
    border-radius: 30px;
    background: #FAFAFA;
    border: 1px solid #ECECEC;
    position: relative;
    padding-left: 21px;
    line-height: 28px;
    color: #7982A7;
    font-size: 12px;
    text-align: center;
    cursor: pointer;
    span{
      position: absolute;
      top: 1px;
      left: 1px;
      display:block;
      height: 24px;
      width: 24px;
      background: #CACACA;
      color: white;
      border-radius: 50%;
      text-align: center;
      line-height: 24px;
      img{
        width: 24px;
        height: 24px;
        border-radius: 50%;
      }
    }
    .del{
      position: absolute;
      top:0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 30px;
      color: white;
      text-align: center;
      background:rgba(130, 130, 130, 0.9);
      display: none;
    }
    &:hover{
      .del{
        display: block;
      }
    }
  }
</style>